/**
 * 
 */
package cn.springsoter.core.tool.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;

import org.springframework.web.multipart.MultipartFile;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kevin
 *
 */
@Slf4j
public class FileUtil extends cn.hutool.core.io.FileUtil{

	/**
	 * 获取上传文件的md5
	 * 
	 * @param file
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	public static String getMd5(MultipartFile file) {
		String result = StringUtil.EMPTY;
		try(InputStream in = file.getInputStream()){
			result = SecureUtil.md5(in);
		} catch(Exception err) {
			log.error("", err);
		}
		return result;
	}

	/**
	 * 获取文件流的md5
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static String getMd5(InputStream in) {
		try{
			return SecureUtil.md5(in);
		} catch(Exception err) {
			log.error("", err);
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (Exception ex) {
					log.error("", ex);
				}
			}
		}
		return StringUtil.EMPTY;
	}
	
	/**
	 * read pem file, delete first and last line, sth. like:<br />
	 * <p>
	 * -----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----
	 * </p>
	 * 
	 * @param filename
	 * @return
	 */
	public static String readPEMFile(String filename) {
		try {
			return readPEMFile(new FileInputStream(filename));
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 读取key文件
	 * 
	 * @param stream
	 * @return
	 */
	public static String readPEMFile(InputStream stream) {
		if (null != stream) {
			BufferedReader in = null;
			StringBuilder ret = new StringBuilder();
			String line;
			try {
				in = new BufferedReader(new InputStreamReader(stream, "ASCII"));
				line = in.readLine();
				while (null != line) {
					if (!(line.startsWith("-----BEGIN ") || line.startsWith("-----END "))) {
						ret.append(line);
						ret.append("\n");
					}
 
					line = in.readLine();
				}
 
				return ret.toString();
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			} finally {
				try {
					stream.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
 
				if (null != in) {
					try {
						in.close();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}
 
		return null;
	}
	
	/**
	 * 读取resources目录下的文件
	 * 解决springboot打成jar包后无法读取resources目录下的文件问题
	 * 
	 * @param filePath	resources目录下的文件路径，如：rsa/rsa.key
	 * @return
	 */
	public static String readResourcesFile(String filePath) {
		try {
		    InputStream stream = FileUtil.class.getClassLoader().getResourceAsStream(filePath);
		    return readPEMFile(stream);
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return null;
	}
}
